package cn.yqx.bankshop.goods.service.impl;

import cn.yqx.bankshop.goods.dao.*;
import cn.yqx.bankshop.goods.dao.es.GoodsDslMapper;
import cn.yqx.bankshop.goods.esutil.ESResult;
import cn.yqx.bankshop.goods.page.PageRequest;
import cn.yqx.bankshop.goods.page.PageResult;
import cn.yqx.bankshop.goods.pojo.*;
import cn.yqx.bankshop.goods.service.GoodSearchService;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;

import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
@Slf4j
public class GoodSearchServiceImpl implements GoodSearchService {
    @Resource
    private RestHighLevelClient client;
    @Autowired
    private GoodsDslMapper goodsDslMapper ;
    @Autowired
    private BuProductTypeMapper productTypeMapper ;
    @Autowired
    private BuGoodsFormatKeyMapper formatKeyMapper ;
    @Autowired
    private BuGoodsFormatValMapper formatValMapper ;

    @Autowired
    BuGoodsMapper goodsMapper ;
    private static final String GOODS_INDEX = "goods_laster";
    private static final String GOODS_NAME_KEY = "goodsName" ;
    private static final int GOODS_PRODUCT_GRADE_ONE =  0 ;
    private static final int GOODS_PRODUCT_GRADE_TWO =  1 ;
    private static final int GOODS_PRODUCT_GRADE_THREE =  2 ;
    private static final int GOODS_PRODUCT_GRADE_FOUR =  3 ;
    private static final int GOODS_PRODUCT_MAX_LENGTH = 4 ;

    @Override
    public void importAll() throws IOException {
        List<BuGoods> list = goodsMapper.selectAll();
        List<BuProductType> productTypeList ;

        for(BuGoods goods: list){
            productTypeList = productTypeMapper.selectGoodTypeByGoodsId(goods.getId()) ;
            if(!productTypeList.isEmpty()){
                goods.setProductGradeOne(productTypeList.get(GOODS_PRODUCT_GRADE_ONE).getProductName());
                goods.setProductGradeTwo(productTypeList.get(GOODS_PRODUCT_GRADE_TWO).getProductName());
                goods.setProductGradeThree(productTypeList.get(GOODS_PRODUCT_GRADE_THREE).getProductName());
                if(productTypeList.size() == GOODS_PRODUCT_MAX_LENGTH ){
                    goods.setProductGradeFour(productTypeList.get(GOODS_PRODUCT_GRADE_FOUR).getProductName());
                }
            }

            List<BuGoodsFormatKey> formatKeys = formatKeyMapper.findFormatKeyByGoodsId(goods.getId()) ;

            if(!formatKeys.isEmpty()){
                for(BuGoodsFormatKey formatKey:formatKeys){
                    List<BuGoodsFormatVal> formatVals = formatValMapper.findFormatValByGoodsId(goods.getId(),formatKey.getFormatKeyIndex()) ;
                    formatKey.setGoodsFormatVals(formatVals);
                }
            }

            goods.setGoodsFormatKeys(formatKeys);
            addGood(goods,String.valueOf(goods.getId()));
        }

    }

    @Override
    public boolean addGood(BuGoods buGoods, String id) throws IOException {
        IndexRequest request = new IndexRequest(GOODS_INDEX).id(id).source(beanToMap(buGoods));
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);



        return false;
    }

    @Override
    public PageResult searchGoods(Map<String,Object> map, PageRequest pageRequest) throws IOException {

        long formIndex = pageRequest.getPageSize()*(pageRequest.getPageNum()-1) ;
        map.put("from",formIndex) ;
        map.put("size",pageRequest.getPageSize()) ;

        ESResult resoult = goodsDslMapper.queryGoods(map) ;
        String jsonStr = JSONObject.toJSONString(resoult);
        return getPageResult(pageRequest,JSON.parseObject(jsonStr),resoult.getTotle());
        
    }


    public static <T> Map<String, Object> beanToMap(T bean) {
        Map<String, Object> map = new HashMap<>();
        if (bean != null) {
            BeanMap beanMap = BeanMap.create(bean);
            for (Object key : beanMap.keySet()) {
                if(beanMap.get(key) != null)
                    if(beanMap.get(key) instanceof  List){
                        map.put(key+"" , JSONObject.toJSON(beanMap.get(key))) ;
                    }else{
                        map.put(key + "", beanMap.get(key));
                    }
            }
        }
        return map;
    }

    /**
     * 调用分页插件完成分页
     * @return
     */
    private PageResult getPageResult(PageRequest pageRequest, JSONObject json,long total) {
        PageResult result = new PageResult() ;
        result.setPageNum(pageRequest.getPageNum());
        result.setContent(json);
        result.setPageSize(pageRequest.getPageSize());
        result.setTotalPages((int)(total/pageRequest.getPageSize())+1);
        result.setTotalSize(total);
        return  result ;
    }
}
